package com.controller.discuss;

import com.domain.*;
import com.server.*;
import com.util.ReceiveCollectionList;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping(value="/discuss")
public class discussController {

    @Resource(name = "spaceService")
    private SpaceService spaceService;

    @Resource(name = "discussService")
    private DiscussService discussService;

    @Resource(name="labelService")
    private LabelService labelService;

    @Resource(name="discussItemService")
    private DiscussItemService discussItemService;

    @Resource(name="commentService")
    private CommentService commentService;

    @Resource(name="replyService")
    private ReplyService replyService;

    @Resource(name="memberService")
    private MemberService memberService;

    @Resource(name = "contributeService")
    private ContributeService contributeService;

    @Resource(name="resourceService")
    private ResourceService resourceService;

    @Resource(name = "userService")
    private UserService userService;

    //通用页面跳转控制器
    @RequestMapping(value = "/{formName}")
    public String f(@PathVariable String formName){
        return formName;
    }

    @RequestMapping(path = "/discussTitle")
    public String discussTitle(Integer memberId,String title,Model model) {
        Discuss discuss=discussService.selectDiscussByTitleAndMemberId(title,memberId);
        model.addAttribute("discuss",discuss);
        return "space-discuss";
    }

    @RequestMapping(path = "/discussUser")
    public String discussUser(Integer memberId,String title,Model model) {
        Discuss discuss=discussService.selectDiscussByTitleAndMemberId(title,memberId);
        model.addAttribute("discuss",discuss);
        return "space-discuss";
    }

    /********************************************************************************************************/
    //跳转讨论区主界面并显示所有讨论话题
    @RequestMapping(value = "/space-discuss")
    public String findAllDiscuss(@RequestParam(value="page",defaultValue="1") int page,
                                 @RequestParam(value="pageSize",defaultValue="8") int pageSize,
                                 HttpSession session, Model model){
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        System.out.println("进入space-discuss");
        List<Discuss> discussesList=discussService.findAllDiscuss(page,pageSize,space_id);
        List<Discuss> discussesList2=discussService.findAllEliteDiscuss(space_id);
        List<Discuss> discussesList3=discussService.findAllCollectDiscuss(space_id);
        int discussTotal = discussService.findDiscussTotal(space_id);
        model.addAttribute("discussTotal",discussTotal);
        System.out.println("****discussTotal==="+discussTotal);
        if(discussTotal==0){
            model.addAttribute("discussTotal",0);
        }else{
            model.addAttribute("discussTotal",discussTotal);
        }
        System.out.println("(discussTotal/pageSize)==="+(discussTotal/pageSize));
        //计算总页数：
        if((discussTotal/pageSize)<1){
            model.addAttribute("pageTotal",1);
        }else {
            if (discussTotal % pageSize != 0) {
                int pageTotal = new Integer(discussTotal / pageSize + 1);
                System.out.println("if--pageTotal===="+pageTotal);
                model.addAttribute("pageTotal", pageTotal);
            } else {
                int pageTotal = new Integer(discussTotal / pageSize);
                System.out.println("else--pageTotal===="+pageTotal);
                model.addAttribute("pageTotal", pageTotal);
            }
        }
        //提示：
        String msg="暂无数据";
        if(discussesList2.size()<1){
            model.addAttribute("msg2",msg);
        }
        if(discussesList3.size()<1){
            model.addAttribute("msg3",msg);
        }
        //查询话题和标签的中间表：
        List<DiscussItem> discussItemList=discussItemService.findAllDiscussItem();
        model.addAttribute("discussItemList",discussItemList);
        //查询所有标签：
        List<Label> labelList=labelService.findAllLabel();
        model.addAttribute("labelList",labelList);
        //设置当前为第一页：
        model.addAttribute("currentPage",page);
        model.addAttribute("discussesList",discussesList);
        model.addAttribute("discussesList2",discussesList2);
        model.addAttribute("discussesList3",discussesList3);
        return "space-discuss";
    }

    //进入添加话题界面
    @RequestMapping(value = "/space-discuss-send")
    public String discussSend(Model model,HttpSession session){
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        List<Member> memberList=memberService.selectAllMember(space_id);
        int discussTotal = discussService.findDiscussTotal(space_id);
        if(discussTotal==0){
            model.addAttribute("discussTotal",0);
        }else{
            model.addAttribute("discussTotal",discussTotal);
        }
        model.addAttribute("memberList",memberList);
        return "/space-discuss-send";
    }

    //添加话题
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public void add(String title,int focus,HttpServletRequest request,
                    HttpServletResponse response,HttpSession session)throws Exception{
        System.out.println("进入控制器add....！！！");
        String type = request.getHeader("X-Requested-With");
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        User user= (User) session.getAttribute("user");
        int user_id=user.getId();
        if ("XMLHttpRequest".equals(type)) {
            //处理AJAX请求，设置响应头信息
            response.setHeader("REDIRECT", "REDIRECT");
            Discuss discuss=new Discuss();
            discuss.setMember_id(user_id);
            Date createdate=new Date();
            discuss.setCreatedate(createdate);
            discuss.setUpdateDate(createdate);
            //得到标题：
            System.out.println("标题title====="+title);
            discuss.setTitle(title);
            System.out.println("特别关注focus====="+focus);
            discuss.setFocus(focus);
            //设置请求和响应的编码统一为UTF-8
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            //拿到编辑器的内容
            //得到富文本框的值：
            String content = request.getParameter("editorValue");
            System.out.println("content内容=="+content);
            if(content!= null){
                //转发到content.jsp
                System.out.println("内容不为空");
                discuss.setContent(content);
            }else {
                System.out.println("内容为空");
                //response.sendRedirect("discuss-detail?id="+new_id+"");
            }
            //设置话题的默认状态：
            discuss.setStatus(1);
            discuss.setSpace_id(space_id);
            discuss.setMember_id(user_id);
            System.out.println(discuss.toString());
            //操作标签：
            List arrList=new ArrayList();//存储数据库已有标签
            ArrayList labelArray=new ArrayList();//存储用户所选标签
            String arr=request.getParameter("arr");
            System.out.println("arr[]===="+arr);
            int count=discussService.addDiscuss(discuss);
            Discuss new_discuss=discussService.findLastId(space_id);
            int new_id=new_discuss.getId();
            System.out.println("new_id="+new_id);
            System.out.println("向话题表中添加"+count+"条【话题】记录");
            //更新session中的话题数：
            Integer discussTotal=(Integer) discussService.findDiscussTotal(space_id);
            session.setAttribute("discussTotal",discussTotal);
            // 根据,(逗号)进行分割,，添加进新数组：
            String[] strArray = arr.split(",");
            for (int i = 0; i < strArray.length; i++) {
                labelArray.add(strArray[i]);
            }
            //数据库查询结果集：
            List<Label> labelList=labelService.findAllLabel();
            for(int j=0;j<labelList.size();j++){
                String labelName=labelList.get(j).getName();
                arrList.add(labelName);//将地址转化为值，存入新的集合
            }
            //比较添加的标签和已选标签，将新增标签添加至label_info：
            for(int j=0;j<labelArray.size();j++){
                if(!arrList.contains(labelArray.get(j))){
                    System.out.println("不相同的标签为："+labelArray.get(j));
                    //将新标签进行添加：
                    Label label=new Label();
                    String name= (String) labelArray.get(j);
                    label.setName(name);
                    int i=labelService.addLabel(label);
                    System.out.println("向标签表中添加了"+i+"个新的【标签】");
                }
            }

            //将已选标签添加至中间表：discussItemService
            int total=0;
            for(int j=0;j<labelArray.size();j++){
                String labelName= (String) labelArray.get(j);
                int label_id=labelService.selectLabelIdByName(labelName);
                DiscussItem discussItem=new DiscussItem();
                discussItem.setDiscuss_id(new_id);
                discussItem.setLabel_id(label_id);
                int amount=discussItemService.addDiscuss_LabelItem(discussItem);
                total=total+amount;
            }
            System.out.println("向话题和标签中间表共插入"+total+"条记录");
            //response.sendRedirect("discuss-detail?id="+new_id+"");
            //需要跳转页面的URL
            response.setHeader("CONTEXTPATH", "discuss-detail?id="+new_id+"");
            System.out.println("跳转到页面discuss-detail");
        } else {
            System.out.println("********else********");
            //其他的http请求，直接重定向就可以了
            response.sendRedirect("space-discuss");
        }

    }

    //主页导航话题搜索，跳转到话题详情界面：
    @RequestMapping(value="/discuss-space-search")
    public String goToDiscuss(@Param("id")int id, @Param("space_id") int space_id,
                              HttpSession session,Model model){
        System.out.println("进入discuss-space-search");
        System.out.println("space_id==="+space_id);
        Space spaceSeesion=spaceService.selectSpaceById(space_id);
        session.setAttribute("space",spaceSeesion);
        model.addAttribute("space",spaceSeesion);
        User user=(User)session.getAttribute("user");
        model.addAttribute("user",user);
        System.out.println("space-search---user"+user);
        session.setAttribute("user",user);
        System.out.println("id========"+id);
        Discuss discuss=discussService.findDiscussByIdAndSpaceId(id, space_id);
        List<Label> labelList=discussService.selectLabelByDiscussId(id);
        List<Comment> commentList=commentService.selectCommentByDiscussId(id);
        List<Reply> replyList=replyService.selectAllReply();
        Space spaceById=spaceService.selectSpaceById(space_id);
        String name=spaceById.getName();
        int userId=spaceById.getUserId();
        Space space=spaceService.selectSpaceByNameAndUserId(name,userId);
        model.addAttribute("space",space);
        //计算资源总数：
        int resourceTotal=resourceService.findResourceTotal(space_id);
        session.setAttribute("resourceTotal",resourceTotal);
        //计算话题总数：
        int discussTotal = discussService.findDiscussTotal(space_id);
        session.setAttribute("discussTotal",discussTotal);
        //计算贡献总数：
        int contributeTotal=contributeService.showContributeTotal(space_id);
        session.setAttribute("contributeTotal",contributeTotal);
        //计算成员总数：
        int memberCount=memberService.findMemberTotal(space_id);
        session.setAttribute("memberCount",memberCount);
        model.addAttribute("discuss",discuss);
        model.addAttribute("labelList",labelList);
        model.addAttribute("commentList",commentList);
        model.addAttribute("replyList",replyList);
        return "space-discuss-detail";
    }


    //点击话题标题，跳转到话题详情界面：
    @RequestMapping(value="/discuss-detail")
    public String goToDiscuss(@Param("id")int id,Model model,HttpSession session){
        System.out.println("进入discuss-detail");
        System.out.println("id========"+id);
        Discuss discuss=discussService.findDiscussById(id);
        List<Label> labelList=discussService.selectLabelByDiscussId(id);
        List<Comment> commentList=commentService.selectCommentByDiscussId(id);
        for(int i=0;i<commentList.size();i++){
            Comment comment=commentList.get(i);
            System.out.println("评论======="+comment);
            User user=comment.getUser();
            System.out.println("用户为======="+user);
        }
        List<Reply> replyList=replyService.selectAllReply();
        model.addAttribute("discuss",discuss);
        model.addAttribute("labelList",labelList);
        model.addAttribute("commentList",commentList);
        model.addAttribute("replyList",replyList);
        return "space-discuss-detail";
    }

    //点击话题详情的删除操作，删除该条话题：
    @RequestMapping(value="/delete")
    public String deleteDiscussById(int id, Model model){
        System.out.println("删除该条话题");
        int i=discussService.deleteDiscussById(id);
        System.out.println("成功删除了"+i+"条记录");
        //跳转到指定控制器:
        return "redirect:space-discuss";
    }

    //点击话题详情的编辑操作，进入修改话题的界面：
    @RequestMapping(value="/goToUpdate")
    public String goToUpdateDiscuss(int id, Model model,HttpSession session){
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        System.out.println("进入goToUpdateDiscuss");
        Discuss discuss=discussService.findDiscussById(id);
        List<Label> labelList=discussService.selectLabelByDiscussId(id);
        int discussTotal = discussService.findDiscussTotal(space_id);
        if(discussTotal==0){
            model.addAttribute("discussTotal",0);
        }else{
            model.addAttribute("discussTotal",discussTotal);
        }
        List<Member> memberList=memberService.selectAllMember(space_id);
        model.addAttribute("memberList",memberList);
        model.addAttribute("discuss",discuss);
        model.addAttribute("labelList",labelList);
        //跳转到指定控制器:
        return "space-discuss-update";
    }

    //点击话题详情的编辑操作，修改该条话题：
    @ResponseBody
    @RequestMapping(value="/updateSubmit",method = RequestMethod.POST)
    public void updateDiscussById(int id,String title,int focus,HttpServletRequest request,
                                    HttpServletResponse response,HttpSession session)throws Exception{
        System.out.println("进入updateDiscussById");
        String type = request.getHeader("X-Requested-With");
        User user=(User)session.getAttribute("user");
        int user_id=user.getId();
        if ("XMLHttpRequest".equals(type)) {
            //处理AJAX请求，设置响应头信息
            response.setHeader("REDIRECT", "REDIRECT");
            Discuss discuss=new Discuss();
            Integer member_id=1;
            discuss.setMember_id(user_id);
            Date createdate=new Date();
            discuss.setCreatedate(createdate);
            discuss.setUpdateDate(createdate);
            //得到标题：
            System.out.println("标题title====="+title);
            discuss.setTitle(title);
            System.out.println("特别关注focus====="+focus);
            discuss.setFocus(focus);
            System.out.println("id====="+id);
            discuss.setId(id);
            //设置请求和响应的编码统一为UTF-8
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            //拿到编辑器的内容
            //得到富文本框的值：
            String content = request.getParameter("editorValue");
            System.out.println("content内容=="+content);
            if(content!= null){
                //转发到content.jsp
                System.out.println("内容不为空");
                discuss.setContent(content);
            }else {
                System.out.println("内容为空");
            }
            //设置话题的默认状态：
            discuss.setStatus(1);
            //得到当前更新时间，更新到话题表：
            Date updateDate=new Date();
            discuss.setUpdateDate(updateDate);
            int count=discussService.updateDiscussById(discuss);
            System.out.println(discuss.toString());
            System.out.println("成功修改【更新时间】，"+count+"条话题记录");

            //操作标签：
            //添加新标签至label_info:
            ArrayList labelArray=new ArrayList();//存储用户所选标签
            String arr=request.getParameter("arr");
            System.out.println("ajax传输的标签数组arr[]===="+arr);
            // 根据,(逗号)进行分割,将修改后的标签添加进新集合：
            String[] strArray = arr.split(",");
            for (int i = 0; i < strArray.length; i++) {
                labelArray.add(strArray[i]);
            }

            //比较添加的标签和已选标签，将新增标签添加至label_info：
            List allList=new ArrayList();
            List<Label> allLabelList=labelService.findAllLabel();
            for(int j=0;j<allLabelList.size();j++){
                String labelName=allLabelList.get(j).getName();
                allList.add(labelName);//将地址转化为值，存入新的集合
            }
            for(int j=0;j<labelArray.size();j++){
                if(!allList.contains(labelArray.get(j))){
                    System.out.println("与标签库进行比较，不相同的标签为："+labelArray.get(j));
                    //将新标签进行添加：
                    Label label=new Label();
                    String name= (String) labelArray.get(j);
                    label.setName(name);
                    int i=labelService.addLabel(label);
                    System.out.println("向标签表中添加了"+i+"个新的【标签】");
                }
            }

            //比较修改前后标签数量：
            int preLabelCount=discussItemService.selectLabelCountByDiscussId(id);
            System.out.println("话题修改前，所选标签数为======"+preLabelCount);
            int laterLabelCount=labelArray.size();
            System.out.println("话题修改后，所选标签数为======"+laterLabelCount);

            //删除中间表discuss_label_info该话题的原有标签：
            int deleteCount=discussItemService.deleteLabelItemByDiscussId(id);
            System.out.println("共删除该话题的原有标签"+deleteCount+"条");

            //将更新后的标签重新添加至中间表：
            int total=0;
            for(int m=0;m<labelArray.size();m++){
                String labelName= (String) labelArray.get(m);
                int label_id=labelService.selectLabelIdByName(labelName);
                DiscussItem discussItem=new DiscussItem();
                discussItem.setDiscuss_id(id);
                discussItem.setLabel_id(label_id);
                int amount=discussItemService.addDiscuss_LabelItem(discussItem);
                total=total+amount;
            }
            System.out.println("向话题和标签中间表插入"+total+"条记录");
            //需要跳转页面的URL
            response.setHeader("CONTEXTPATH", "discuss-detail?id="+id+"");
        } else {
            //其他的http请求，直接重定向就可以了
            response.sendRedirect("space-discuss");
        }
        //跳转到指定控制器:
        //需要跳转页面的URL
        response.setHeader("CONTEXTPATH", "discuss-detail?id="+id+"");
    }


    //点击讨论区主界面的搜索按钮，跳转到搜索话题界面：
    @RequestMapping(value = "/goToSearch",method = RequestMethod.POST)
    public String goToSearchDiscuss(Discuss discuss,Model model,HttpSession session){
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        System.out.println("title===="+discuss.getTitle());
        discuss.setSpace_id(space_id);
        List<Discuss> discussesList=discussService.findDiscussByParam(discuss);
        model.addAttribute("discussesList",discussesList);
        int discussTotal = discussService.findDiscussTotal(space_id);
        if(discussTotal==0){
            model.addAttribute("discussTotal",0);
        }else{
            model.addAttribute("discussTotal",discussTotal);
        }
        //返回搜索条件：
        model.addAttribute("discuss",discuss);
        return "space-discuss-search";
    }

    //在讨论区搜索话题界面：
    @RequestMapping(value = "/searchSubmit",method = RequestMethod.POST)
    public String searchDiscuss(@Param("authorName") String authorName,Discuss discuss,String name,
                                Model model,HttpSession session){
        System.out.println("进入searchDiscuss");
        Space space= (Space) session.getAttribute("space");
        //通过作者名查询id:
        int author_id=userService.selectUserIdByName(authorName);
        User user=userService.selectUserById(author_id);
        authorName=user.getUsername();
        model.addAttribute("authorName",authorName);
        int space_id=space.getId();
        discuss.setSpace_id(space_id);
        /***********中间集合**************/
        List list1=new ArrayList();//存放根据参数查询结果的id
        List list2=new ArrayList();//存放根据标签名查询的结果的id
        List<Discuss> discussesList=new ArrayList<Discuss>();//存放list1和list2结果交集的讨论
        /*************************************************/
        List<Discuss> discussesParamList=discussService.findDiscussByParam(discuss);
        System.out.println("共查询出==="+discussesParamList.size()+"条结果");
        for(int i=0;i<discussesParamList.size();i++){
            int paramId=discussesParamList.get(i).getId();
            list1.add(paramId);
        }
        System.out.println("搜索标签名name===="+name);
        List<Discuss> discussByLabelList=labelService.selectDiscussByLikeLabelName(name);
        for(int i=0;i<discussByLabelList.size();i++){
            int paramId=discussByLabelList.get(i).getId();
            list2.add(paramId);

        }

        for(int i=0;i<list1.size();i++){
            System.out.println("通过（讨论参数）搜索的结果：====="+list1.get(i));
        }

        for(int i=0;i<list2.size();i++){
            System.out.println("通过标签名搜索的结果：====="+list2.get(i));
        }
        // 获取交集
        ReceiveCollectionList receiveCollectionList=new ReceiveCollectionList();
        List collectionList = receiveCollectionList.receiveCollectionList(list1,list2);
        Iterator collectionIterator = collectionList.iterator();
        System.out.println("===================交集===================");
        while (collectionIterator.hasNext()) {
            Integer id=(Integer)collectionIterator.next();
            System.out.println("查询结果的交集====="+id);
            Discuss discuss2=discussService.findDiscussById(id);
            discussesList.add(discuss2);
        }

        if(discussesList.size()<1){
            String msg="暂无数据";
            model.addAttribute("msg",msg);
        }
        int discussTotal = discussService.findDiscussTotal(space_id);
        if(discussTotal==0){
            model.addAttribute("discussTotal",0);
        }else {
            model.addAttribute("discussTotal", discussTotal);
        }
        //返回搜索条件：
        model.addAttribute("discuss",discuss);
        model.addAttribute("discussesList",discussesList);
        return "space-discuss-search";
    }

    //修改话题状态，设为精华：
    @RequestMapping(value = "/setEssence")
    public String setEssenceDiscuss(@Param("id")int id,HttpSession session){
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        System.out.println("进入setEssenceDiscuss");
        System.out.println("当前想要设为精华贴的id=="+id);
        Discuss before_discusses=discussService.findDiscussById(id);
        int before_status=before_discusses.getStatus();
        System.out.println("该话题的当前状态："+before_status);
        //先判断是否即为精华+收藏：
        if(before_status==4){
            before_discusses.setStatus(3);
            int i=discussService.updateDiscussById(before_discusses);
        }else{
            //判断是否为收藏状态：
            if(before_status!=3){
                //判断该话题的状态
                if(before_status==1){//此时无话题状态
                    before_discusses.setStatus(2);
                    int i=discussService.updateDiscussById(before_discusses);
                }
                if(before_status==2){//此时无话题状态
                    before_discusses.setStatus(1);
                    int i=discussService.updateDiscussById(before_discusses);
                }
            }else{//当前话题已为收藏状态
                before_discusses.setStatus(4);
                int i=discussService.updateDiscussById(before_discusses);
            }
        }
        return "redirect:discuss-detail?id="+id+"";
    }

    //修改话题状态，设为收藏：
    @RequestMapping(value = "/setCollect")
    public String setCollectDiscuss(@Param("id")int id,HttpSession session){
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        System.out.println("进入setCollectDiscuss");
        System.out.println("当前想要设为精华贴的id=="+id);
        Discuss before_discusses=discussService.findDiscussById(id);
        int before_status=before_discusses.getStatus();
        System.out.println("该话题的当前状态："+before_status);
        if(before_status==4){
            before_discusses.setStatus(2);
            int i=discussService.updateDiscussById(before_discusses);
        }else{
            //判断是否为收藏状态：
            if(before_status!=2){
                //判断该话题的状态
                if(before_status==1){//此时无话题状态
                    before_discusses.setStatus(3);
                    int i=discussService.updateDiscussById(before_discusses);
                }
                if(before_status==3){//此时无话题状态
                    before_discusses.setStatus(1);
                    int i=discussService.updateDiscussById(before_discusses);
                }
            }else{//当前话题已为收藏状态
                before_discusses.setStatus(4);
                int i=discussService.updateDiscussById(before_discusses);
            }
        }
        return "redirect:discuss-detail?id="+id+"";
    }


    //根据创建时间进行排序显示：
    @RequestMapping(value = "/descCreateDate")
    public String descCreateDate(@RequestParam(value="page",defaultValue="1") int page,
                                 @RequestParam(value="pageSize",defaultValue="8") int pageSize,
                                 Model model,HttpSession session){
        System.out.println("进入descCreateDate");
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        List<Discuss> discussesList=discussService.descCreateDate(space_id);
        List<Discuss> discussesList2=discussService.findAllEliteDiscuss(space_id);
        List<Discuss> discussesList3=discussService.findAllCollectDiscuss(space_id);
        int discussTotal = discussService.findDiscussTotal(space_id);
        if(discussTotal==0){
            model.addAttribute("discussTotal",0);
        }else{
            model.addAttribute("discussTotal",discussTotal);
        }
        //计算总页数：
        if((discussTotal/pageSize)<1){
            model.addAttribute("pageTotal",1);
        }else {
            if (discussTotal % pageSize != 0) {
                int pageTotal = new Integer(discussTotal / pageSize + 1);
                model.addAttribute("pageTotal", pageTotal);
            } else {
                int pageTotal = new Integer(discussTotal / pageSize);
                model.addAttribute("pageTotal", pageTotal);
            }
        }
        //设置当前为第一页：
        model.addAttribute("currentPage",page);
        String msg="暂无数据";
        if(discussesList2.size()<1){
            model.addAttribute("msg2",msg);
        }
        if(discussesList3.size()<1){
            model.addAttribute("msg3",msg);
        }
        //查询话题和标签的中间表：
        List<DiscussItem> discussItemList=discussItemService.findAllDiscussItem();
        model.addAttribute("discussItemList",discussItemList);
        //查询所有标签：
        List<Label> labelList=labelService.findAllLabel();
        model.addAttribute("labelList",labelList);
        //设置排序选择：
        String sort="created";
        model.addAttribute("sort",sort);
        model.addAttribute("discussesList",discussesList);
        model.addAttribute("discussesList2",discussesList2);
        model.addAttribute("discussesList3",discussesList3);
        return "space-discuss";
    }

    //根据更新时间进行排序显示：
    @RequestMapping(value = "/descUpdateDate")
    public String descUpdateDate(@RequestParam(value="page",defaultValue="1") int page,
                                 @RequestParam(value="pageSize",defaultValue="8") int pageSize,
                                 Model model,HttpSession session){
        System.out.println("进入descUpdateDate");
        Space space= (Space) session.getAttribute("space");
        int space_id=space.getId();
        List<Discuss> discussesList=discussService.descUpdateDate(space_id);
        List<Discuss> discussesList2=discussService.findAllEliteDiscuss(space_id);
        List<Discuss> discussesList3=discussService.findAllCollectDiscuss(space_id);
        int discussTotal = discussService.findDiscussTotal(space_id);
        if(discussTotal==0){
            model.addAttribute("discussTotal",0);
        }else{
            model.addAttribute("discussTotal",discussTotal);
        }

        //计算总页数：
        if((discussTotal/pageSize)<1){
            model.addAttribute("pageTotal",1);
        }else {
            if (discussTotal % pageSize != 0) {
                int pageTotal = new Integer(discussTotal / pageSize + 1);
                model.addAttribute("pageTotal", pageTotal);
            } else {
                int pageTotal = new Integer(discussTotal / pageSize);
                model.addAttribute("pageTotal", pageTotal);
            }
        }
        //查询话题和标签的中间表：
        List<DiscussItem> discussItemList=discussItemService.findAllDiscussItem();
        model.addAttribute("discussItemList",discussItemList);
        //查询所有标签：
        List<Label> labelList=labelService.findAllLabel();
        model.addAttribute("labelList",labelList);
        //设置当前为第一页：
        model.addAttribute("currentPage",page);
        String msg="暂无数据";
        if(discussesList2.size()<1){
            model.addAttribute("msg2",msg);
        }
        if(discussesList3.size()<1){
            model.addAttribute("msg3",msg);
        }

        //设置排序选择：
        String sort="updated";
        model.addAttribute("sort",sort);
        model.addAttribute("discussesList",discussesList);
        model.addAttribute("discussesList2",discussesList2);
        model.addAttribute("discussesList3",discussesList3);
        return "space-discuss";
    }

    @RequestMapping(value="/goToComment",method = RequestMethod.POST)
    public String goToComment(int discuss_id,int author_id,Comment comment,HttpSession session){
        System.out.println("**************进入goToComment控制器******************");
        System.out.println("话题id:"+discuss_id);
        System.out.println("发布者id:"+comment.getAuthor_id());
        System.out.println("内容:"+comment.getContent());
        Date date=new Date();
        comment.setCreatedate(date);
        comment.setAuthor_id(author_id);
        comment.setDiscuss_id(discuss_id);
        int i=commentService.addComment(comment);
        System.out.println("成功添加的"+i+"条评论");
        return "redirect:discuss-detail?id="+discuss_id+"";
    }

    @RequestMapping(value="/deleteComment")
    public String deleteComment(int comment_id,int discuss_id,HttpSession session){
        System.out.println("要删除的评论id为"+comment_id);
        int i=commentService.deleteCommentById(comment_id);
        System.out.println("成功删除了"+i+"条评论");
        int j=replyService.deleteReplyByCommentId(comment_id);
        System.out.println("成功删除了id为："+comment_id+"的评论"+j+"条回复");
        return "redirect:discuss-detail?id="+discuss_id+"";
    }

    @RequestMapping(value="/deleteReply")
    public String deleteReply(int reply_id,int discuss_id,HttpSession session){
        System.out.println("要删除的回复id为"+reply_id);
        int i=replyService.deleteReplyById(reply_id);
        System.out.println("成功删除了"+i+"条评论");
        return "redirect:discuss-detail?id="+discuss_id+"";
    }

    @RequestMapping(value="/reply",method = RequestMethod.POST)
    public String replyComment(int discuss_id,int comment_id,int member_id,Reply reply,HttpSession session) {
        System.out.println("*******进入/reply控制器*****");
        User user=(User)session.getAttribute("user");
        int author_id=user.getId();
        System.out.println("话题id:"+discuss_id);
        System.out.println("回复的话题id:"+comment_id);
        System.out.println("回复内容:"+reply.getContent());
        Date date=new Date();
        reply.setCreatedate(date);
        reply.setAuthor_id(author_id);
        //回复给那位成员:
        System.out.println("回复给id为成员===="+member_id);
        reply.setMember_id(member_id);
        reply.setComment_id(comment_id);
        int i=replyService.addReply(reply);
        System.out.println("成功回复了"+i+"条评论");
        return "redirect:discuss-detail?id="+discuss_id+"";
    }
}
